<?php

namespace Aoe\Util\Manager;

use Exception;

/**
 * # 子对象管理器(缓存器)
 *   ！！！ 所有键都小写
 *
 * @template T
 */
abstract class Collection
{
    /**
     * @var array<T>|false 对象缓存 false表示不缓存
     */
    protected false | array $objects = [];
    
    /**
     * ## 获取子对象实例
     *
     * @param mixed $name 子对象类名称
     *
     * @return ?T
     * @throws Exception
     */
    public function get(string $name): ?object
    {
        $name  = strtolower($name);
        // 缓存该对象
        if (!isset($this->objects[$name])) $this->objects[$name] = $this->create_object($name);
        
        return $this->objects[$name];
    }
    
    /**
     * ## 创建对象
     *
     * @param mixed $name
     *
     * @return ?T
     * @throws Exception
     */
    abstract protected function create_object(string $name): ?object;
    
    public function has(string $name): bool
    {
        $name  = strtolower($name);
        return isset($this->objects[$name]);
    }
}